package com.igoal.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.igoal.entity.DataStatus;
import com.igoal.entity.UserGoalEntry;
import com.igoal.entity.UserGoalPk;

@Repository("userGoalEntryDAO")
public class UserGoalEntryDAOImpl extends
		GenericDaoHibernate<UserGoalEntry, Long> implements UserGoalEntryDAO {

	public UserGoalEntryDAOImpl() {
		super(UserGoalEntry.class);
	}
	
	public List<UserGoalEntry> findByFK(Long userId, Long goalId) {
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalEntry.class);
		dc.add(Restrictions.eq("userGoal.pk.user.id", userId));
		dc.add(Restrictions.eq("userGoal.pk.goal.id", goalId));
		getByStatus(dc, DataStatus.USING);
		List<UserGoalEntry> result = findByCriteria(dc);		
		return result;
	}

	public List<UserGoalEntry> findByFK(UserGoalPk fk) {
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalEntry.class);
		dc.add(Restrictions.eq("userGoal.pk", fk));
		getByStatus(dc, DataStatus.USING);
		List<UserGoalEntry> result = findByCriteria(dc);	
		return result;
	}

	public List<UserGoalEntry> listEntriesByUser(Long userId,
			int numberOfEntries, String orderBy) {
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalEntry.class);
		dc.add(Restrictions.eq("userGoal.pk.user.id", userId));
		getByStatus(dc, DataStatus.USING);
		
		if(orderBy != null){
			dc.addOrder(Order.desc(orderBy));
		}
				
		List<UserGoalEntry> result;
		if(numberOfEntries >= 0)
			result = findByCriteria(dc, 0, numberOfEntries);
		else
			result = findByCriteria(dc);
		
		return result;
	}

	public List<UserGoalEntry> listEntriesByGoal(Long goalId,
			int numberOfEntries, String orderBy) {
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalEntry.class);
		dc.add(Restrictions.eq("userGoal.pk.goal.id", goalId));
		getByStatus(dc, DataStatus.USING);
		
		if(orderBy != null){
			dc.addOrder(Order.desc(orderBy));
		}
				
		List<UserGoalEntry> result;
		if(numberOfEntries >= 0)
			result = findByCriteria(dc, 0, numberOfEntries);
		else
			result = findByCriteria(dc);
		
		return result;
	}
	
	public int countEntries(Long userId, Long goalId){
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalEntry.class);
		if(userId != null && userId > 0L){
			dc.add(Restrictions.eq("userGoal.pk.user.id", userId));
		}
		if(goalId != null && goalId > 0L){
			dc.add(Restrictions.eq("userGoal.pk.goal.id", goalId));
		}
		getByStatus(dc, DataStatus.USING);
				
		return countByCriteria(dc);
	}
}
